const router = require('../router');
const Result = require('../../config/result');
const {databaseToken} = require('../../config/databaseapi')
const {checkRegister} = require("../../config/checking");
const {getToken} = require('../../token/jwt')
const Auth = require("../../token/auth");

// 注册接口
router.post('/register', async ctx => {
  checkRegister(ctx)
  const {account, password, nickname, picUrl} = ctx.request.body
  const query = `db.collection('account').where({account:'${account}'}).get()`
  try {
    const data = await databaseToken.query(query)
    if (data.errcode === 0) {
      if (data.data.length === 0) {
        const query = `db.collection('account').add({
            data:[{
            account:'${account}',
            password:'${password}',
            phone:'${account}',
            nickname:'${nickname}',
            picUrl:'${picUrl}'
          }]})`
        const data = await databaseToken.add(query)
        new Result(ctx, '注册成功', 200).answer()
      } else {
        new Result(ctx, '账号已存在', 400).answer()
      }
    } else {
      new Result(ctx, '注册失败', 500).answer()
    }
  } catch (e) {
    console.log(e)
    new Result(ctx, '注册失败', 500).answer()
  }
})

// 登录接口
router.post('/login', async ctx => {
  let {account, password} = ctx.request.body
  const query = `db.collection('account').where({account:'${account}',password:'${password}'}).get()`
  try {
    const data = await databaseToken.query(query)
    if (data.errcode === 0) {
      if (data.data.length === 0) {
        new Result(ctx, '账号或密码错误', 202).answer()
      } else {
        const {_id} = JSON.parse(data.data[0])
        const token = getToken(_id)
        console.log(token)
        new Result(ctx, '登录成功', 200, {token}).answer()
      }
    } else {
      new Result(ctx, '登录失败', 500).answer()
    }
  } catch (e) {
    new Result(ctx, '登录失败', 500).answer()
  }
})

router.get('/test', new Auth().m, async ctx => {
  console.log(ctx.auth) // 获取token中的信息,userId
  new Result(ctx, '测试成功', 200).answer()
})

module.exports = router.routes();